//
// Created by syj on 2023/7/26.
//
#include <signal.h>
#ifndef _WIN64
#include <execinfo.h>
#endif
#include "logger.h"
#include "cJSON/cJSON.h"

typedef void (*SIGNALHANDLER)(int);

constexpr int BacktraceDeep{30};
static bool gQuit = false;

void signal_hanlder(int signo)
{
#ifndef _WIN64
    int size = 0;
    char ** strings = nullptr;
    void *array[BacktraceDeep];
    size = backtrace(array, BacktraceDeep);
    strings = (char**)backtrace_symbols(array,size);
    if (nullptr != strings)
    {
        for (int i = 0; i < size; ++i) {
            Logger_Info("trace:[{}]:{}", i, strings[i]);
        }
        free(strings);
        strings = nullptr;
    }
#endif
    if (SIGTERM == signo || SIGINT == signo || SIGSEGV == signo
#ifndef _WIN64
               || SIGQUIT == signo
#endif
               )
    {
        Logger_Warn("signal_handler signo:{}", signo);
        gQuit = true;
    }
}
#ifndef _WIN64
void signal_action(int signo, SIGNALHANDLER func)
{
    struct sigaction act,oact;
    act.sa_handler = func;
    sigemptyset(&act.sa_mask);
    act.sa_flags = 0;
    if (SIGALRM != signo)
    {
        act.sa_flags != SA_RESTART;
    }
    sigaction(signo,&act,&oact);
}
#endif
int main(int argc, const char * argv[])
{
    Logger_Init("../loggerConfig.json");
#ifndef _WIN64
    signal_action(SIGTERM, signal_hanlder);
    signal_action(SIGINT, signal_hanlder);
    signal_action(SIGQUIT, signal_hanlder);
    signal_action(SIGSEGV, signal_hanlder);
    signal_action(SIGPIPE, signal_hanlder);
#else

#endif
    while(!gQuit)
    {
        Logger_Error("########start########");
//        Logger_Trace("123");
//        Logger_Debug("123");
//        Logger_Info("123");
//        Logger_Warn("123");
//        Logger_Error("123");
//        Logger_Critical("123");
//        SPDLOG_DEBUG("debug test");
//        SPDLOG_TRACE("trace test");
//        Logger_Error("########end########");
    }
}
